<template>
	<view class="page">
		<u-gap height="20"></u-gap>
		<view class="section margin0">
			<view class="title">选择视频素材</view>
			<view class="chooseVue margin20 flex-between align-center" @click="show = true">
				<text v-if="uploadVideoUrl && videoId" style="color: #000">视频素材-ID{{ videoId }}</text>
				<text v-else>请选择视频素材</text>
				<image src="../../static/more.png" style="width: 45rpx; height: 45rpx"></image>
			</view>
		</view>
		<!-- 设置声音名称 -->
		<view class="inpVue margin30">
			<view class="label">设置视频名称</view>
			<input type="text" placeholder="请设置视频名称" v-model="name" />
		</view>
		<!-- 添加文案 -->
		<view class="inpVue margin30">
			<view class="label">添加文案</view>
			<view class="margin20">
				<u-subsection :list="tabs" :current="current" button-color="#F8C329" active-color="#fff" height="88"
					bg-color="#f5f5f5" @change="change"></u-subsection>
			</view>
			<textarea placeholder="请输入音频文案" maxlength="-1" v-if="current === 0" v-model="text"></textarea>

			<!-- 	<view class="audioVue flex align-center margin20" v-if="current===1">
				<view class="playBtn relative" @click="uploadAudioPlayFun(fileUrl)">
					<image src="" style="width: 44rpx; height: 44rpx;" class="absolute-auto" v-if="!isUploadPlay"></image>
					<image src="" style="width: 44rpx; height: 44rpx;" class="absolute-auto" v-else></image>
				</view>
				<view class="flex-1 flex-between align-center padding-row20" @click="chooseAudio()">
					<text v-if="audioProgress===0">点击添加音频</text>
					<text v-else-if="audioProgress===100" style="color: #000;">{{ fileName }}</text>
					<u-line-progress active-color="#F8C329" inactive-color="#ccc" :percent="audioProgress" :striped="true" :striped-active="true" height="36" style="width: 450rpx;" v-else></u-line-progress>
					<image src="../../static/more.png" style="width: 40rpx; height: 40rpx;"></image>
				</view>
			</view> -->

			<view class="flex align-center" v-if="current === 1">
				<textarea placeholder="请输入音频文案需求" maxlength="-1" class="flex-1" v-model="aiText"></textarea>
				<view class="aiBtn text-center" @click="aiBtnFun()">Ai生成</view>
			</view>
		</view>

		<!-- 选择音色 -->
		<view class="inpVue margin30" v-if="current != 2">
			<view class="label" style="padding: 0">选择音色</view>
			<view class="chooseVue margin30 flex-between align-center padding-row20" @click="show50 = true">
				<text v-if="selectId && voiceName">{{ voiceName }}-{{ voiceSex }}</text>
				<text v-else>选择音色</text>
				<image src="../../static/more.png" style="width: 45rpx; height: 45rpx"></image>
			</view>
		</view>

		<!-- 开始生成视频按钮 -->
		<view class="inpVue margin50">
			<view class="text-center margin0" style="color: #333; font-weight: 600">当前剩余{{ aiVideoPoints }}积分</view>
			<view class="startBtn margin20" @click="startFun()">开始生成视频</view>
			<view class="flex-center align-center margin20">
				<u-checkbox v-model="checked" active-color="#F8C329"
					label-size="28">完成前两次公开训练后，您每次将获得最高100积分</u-checkbox>
			</view>
		</view>

		<u-gap height="30"></u-gap>

		<!-- 选择视频素材 -->
		<u-popup v-model="show" mode="left">
			<view class="popupVue">
				<view class="flex-between align-center">
					<view class="h2">我的视频素材</view>
					<view class="upload" @click="chooseVideo()" v-if="videoProgress === 0">
						<text>上传素材</text>
					</view>
					<u-line-progress active-color="#F8C329" :percent="videoProgress" style="width: 150rpx"
						v-else></u-line-progress>
				</view>
				<!-- 无数据显示 -->
				<view class="w100 flex-column align-center padding-column20 fixed-auto" v-if="videoList.length === 0">
					<image src="https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/assets/empty.png"
						style="width: 256rpx; height: 256rpx"></image>
					<text style="color: #81868e">暂无视频素材</text>
				</view>
				<scroll-view scroll-y class="scrollVue">
					<view class="videoVue flex-between flex-wrap">
						<view class="videoItem" v-for="(item, index) in videoList" :key="index">
							<view class="relative" style="width: 270rpx; height: 270rpx"
								@click.stop="selectVideo(item)">
								<image :src="item.videoUrl +
									'?x-oss-process=video/snapshot,t_1,f_jpg,m_fast,ar_auto'
									" style="width: 270rpx; border-radius: 12rpx 12rpx 0 0" mode="aspectFill"></image>
								<view class="absolute" @click.stop="$tools.router('../play', item.videoUrl)" style="
                    width: 60rpx;
                    height: 60rpx;
                    border-radius: 12rpx;
                    background: rgba(0, 0, 0, 0.3);
                    top: 20rpx;
                    right: 20rpx;
                  ">
									<u-icon name="play-right-fill" color="#fff" size="30" class="absolute-auto"
										style="line-height: 1"></u-icon>
								</view>
							</view>
							<view class="botVue flex-between align-center" :class="{ active: videoId === item.id }">
								<text>ID: {{ item.id }}</text>
								<view class="btn" @click.stop="
									oprationId = item.id;
								show20 = true;
								">删除</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<!-- 选择音色 -->
		<u-popup v-model="show50" mode="left">
			<view class="popupVue">
				<view class="flex-between align-center">
					<view class="h2">选择音色</view>
					<view class="upload" @click="$tools.route('./voice')">去训练</view>
				</view>
				<scroll-view scroll-y class="scrollVue">
					<view class="voiceVue">
						<u-subsection :list="tabList" :current="voiceCurrent" height="80" button-color="#fff"
							active-color="#F8C329" bg-color="#f5f5f5" @change="voiceChange"></u-subsection>
						<!-- 无数据显示 -->
						<view class="w100 flex-column align-center padding-column20 fixed-auto"
							v-if="voiceList.length === 0">
							<image src="https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/assets/empty.png"
								style="width: 256rpx; height: 256rpx"></image>
							<text style="color: #81868e">无音色选择</text>
						</view>
						<view class="item flex align-center margin20" v-for="(item, index) in voiceList" :key="index"
							v-if="item.statusDesc === '训练成功'">
							<view class="playBtn relative" @click="playFun(item.url, item.id)">
								<image
									src=""
									style="width: 44rpx; height: 44rpx" class="absolute-auto" v-if="audioId != item.id">
								</image>
								<image
									src=""
									style="width: 44rpx; height: 44rpx" class="absolute-auto" v-else></image>
							</view>
							<view class="content flex-between padding-row20 align-center" @click="selectAudio(item)">
								<text style="color: #81868e">{{ item.name }}-{{ item.sex }}</text>
								<image src="../../static/radio1.png" style="width: 40rpx; height: 40rpx"
									v-if="selectId == item.id"></image>
								<image src="../../static/radio0.png" style="width: 40rpx; height: 40rpx" v-else>
								</image>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<!-- 删除声音 -->
		<u-modal v-model="show20" content="确认删除该视频素材" confirm-color="#d81e06" :show-cancel-button="true"
			@confirm="deleteFun"></u-modal>

		<u-action-sheet :list="actions" v-model="show60" @click="handleClick"></u-action-sheet>
	</view>
</template>
<!-- { name: "音频添加" } -->
<script>
import baseUrl from "@/common/url.js";
import { mapState } from "vuex";
export default {
	data() {
		return {
			name: "",
			tabs: [{ name: "文本添加" }, { name: "AI生成文案" }],
			tabList: [{ name: "我的" }, { name: "推荐" }, { name: "他人" }],
			current: 0,
			text: "",
			aiText: "",
			videoProgress: 0,
			audioProgress: 0,
			fileName: "",
			fileUrl: "",
			show: false,
			show20: false,
			show50: false,
			show60: false,
			videoList: [],
			videoId: "",
			uploadVideoUrl: "",
			innerAudioContext: null,
			isUploadPlay: false,
			voiceList: [],
			voiceType: "我的",
			voiceCurrent: 0,
			audioId: "",
			audioContext: null,
			soundUrl: "",
			voiceName: "",
			voiceSex: "",
			soundOriginalText: "",
			aiVideoPoints: 0,
			voiceFileUrl: "",
			checked: false,
			selectId: "",
			oprationId: "",
			oprationUrl: "",
			actions: [{ text: "删除该视频" }, { text: "分享给好友" }],
		};
	},

	async onLoad() {
		await this.getVideoList();
		await this.getVoiceList();
		await this.getPoint();
	},

	computed: {
		...mapState({
			user: (state) => state.user,
		}),
	},

	methods: {
		change(e) {
			this.current = e;
		},
		toOpration(id, url) {
			this.oprationId = id;
			this.oprationUrl = url;
			this.show60 = true;
		},

		// 分享
		shareFun() {
			let that = this;
			uni.downloadFile({
				url: that.oprationUrl, // 视频地址
				success(res) {
					wx.shareVideoMessage({
						videoPath: res.tempFilePath,
					});
				},
				fail(err) {
					console.log(err);
				},
			});
		},

		// 开始生成视频第一步
		async startFun() {
			let that = this;
			if (that.aiVideoPoints < 30) return that.$u.toast("积分不足，请充值");
			if (!that.name) return that.$u.toast("请设置视频名称");
			if (!that.uploadVideoUrl) return that.$u.toast("请选择视频");
			if (that.current === 0 && !that.text)
				return that.$u.toast("请输入音频文案");
			if (that.current === 1 && !that.aiText)
				return that.$u.toast("请输入音频文案");
			if (that.current !== 2 && !that.soundUrl)
				return that.$u.toast("请选择音色");
			if (that.current === 2 && !that.voiceFileUrl)
				return that.$u.toast("请添加音频");
			uni.showLoading();
			const res = await that.$request(
				"/shuziren/userVideo/startAudio",
				{
					name: that.name,
					publiced: that.checked,
					uploadVideoUrl: that.uploadVideoUrl,
					kouXing: -10,
					soundUrl: [that.soundUrl, that.soundUrl, that.voiceFileUrl][
						that.current
					],
					flagHd: 0,
					soundText: [that.text, that.aiText, ""][that.current],
					soundOriginalText: that.soundOriginalText,
					type: that.current === 2 ? 1 : 2,
					subtitle: 0,
				},
				"POST",
				"application/json"
			);
			if (res.code === 200) {
				that.name = "";
				that.soundUrl = "";
				that.soundOriginalText = "";
				that.voiceFileUrl = "";
				that.text = "";
				that.aiText = "";
				that.checked = false;
				that.voiceName = "";
				that.voiceSex = "";
				uni.hideLoading();
				that.$u.toast("开始生成");
				setTimeout(() => {
					that.$tools.route("../mine/myVideo");
				}, 1000);
			} else {
				uni.hideLoading();
				that.$u.toast(res.msg);
			}
		},

		// 获取积分
		async getPoint() {
			const res = await this.$request(
				"/aiet-user-center/user/points/summary",
				{},
				"GET"
			);
			if (res.code === 200) {
				this.aiVideoPoints = res.data.aiVideoPoints;
			}
		},

		// 使用视频素材
		selectVideo(item) {
			if (this.videoId === item.id) {
				this.videoId = "";
				this.uploadVideoUrl = "";
				return;
			}
			this.videoId = item.id;
			this.uploadVideoUrl = item.videoUrl;
			this.show = false;
		},

		// 使用音色
		selectAudio(item) {
			if (this.selectId === item.id) {
				this.voiceName = "";
				this.voiceSex = "";
				this.soundUrl = "";
				this.soundOriginalText = "";
				this.selectId = "";
				return;
			}
			this.selectId = item.id;
			this.voiceName = item.name;
			this.voiceSex = item.sex;
			this.soundUrl = item.url;
			this.soundOriginalText = item.soundText;
			this.show50 = false;
		},

		// 删除视频素材
		async deleteFun() {
			const res = await this.$request(
				"/shuziren/userUploadVideo",
				{
					id: this.oprationId,
				},
				"DELETE"
			);
			if (res.code === 200) {
				this.$u.toast("删除成功");
				this.getVideoList();
			}
		},

		// 获取上传视频列表
		async getVideoList() {
			const res = await this.$request(
				"/shuziren/userUploadVideo",
				{
					pageNum: 0,
					pageSize: 30,
				},
				"GET"
			);
			if (res.code === 200) {
				this.videoList = res.data.content;
			}
		},

		// 获取音色列表
		async getVoiceList() {
			const res = await this.$request(
				"/shuziren/soundTrain/list",
				{
					type: this.voiceType,
					pageNum: 0,
					pageSize: 100,
				},
				"GET"
			);
			console.log("1111111:", res.data.content);

			if (res.code === 200) this.voiceList = res.data.content;
		},

		voiceChange(e) {
			this.voiceType = this.tabList[e].name;
			this.getVoiceList();
		},

		// 播放列表音频
		playFun(url, id) {
			if (this.audioId === id) {
				this.audioContext.pause();
				this.audioId = 0;
				return;
			}
			if (this.audioId && this.audioId != id) {
				this.audioContext.destroy();
				this.audioContext = null;
				this.audioId = 0;
			}
			this.audioId = id;
			this.audioContext = uni.createInnerAudioContext();
			this.audioContext.autoplay = true;
			this.audioContext.src = url;
			this.audioContext.onPlay(() => {
				console.log("开始播放");
			});
			this.audioContext.onEnded(() => {
				console.log("播放结束");
				this.audioId = 0;
				this.audioContext.destroy();
				this.audioContext = null;
			});
		},

		async aiBtnFun() {
			if (!this.aiText) return this.$u.toast("请输入文案")
			uni.showLoading()
			try {
				const res = await this.$request("/shuziren/aichat/answer", {
					applicationId: "348f9058-8780-11ef-8828-0242ac110002",
					question: this.aiText
				})
				if (res.code === 200) {
					console.log(res)
					uni.hideLoading()
					this.aiText = res.data
				} else {
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			} catch (error) {
				uni.hideLoading();
				console.error("请求失败:", error);
				this.$u.toast("请求失败，请重试");
			}
		},
		// 选择音频文件
		chooseAudio() {
			let that = this;
			wx.chooseMessageFile({
				extension: [".wav", ".mp3", ".m4a", ".amr"],
				success(res) {
					const tempFilePaths = res.tempFiles[0];
					console.log(tempFilePaths);
					const uploadTask = uni.uploadFile({
						url: baseUrl.url + "/aiet-file-center/file",
						filePath: tempFilePaths.path,
						name: "file",
						formData: {
							path: "shuziren/audio",
						},
						success(uploadRes) {
							let data = JSON.parse(uploadRes.data);
							console.log(data);
							if (data.code === 200) {
								that.fileName = tempFilePaths.name;
								that.fileUrl = data.data.fileUrl;
								console.log(that.fileName, that.fileUrl);
							} else {
								that.$u.toast(data.msg);
							}
						},
						fail(uploadError) {
							console.log(uploadError);
							that.$u.toast("上传失败");
						},
					});
					console.log(uploadTask);
					uploadTask.onProgressUpdate((res) => {
						that.audioprogress = res.progress;
						console.log(that.audioprogress);
					});
				},
			});
		},

		// 保存视频
		keepVideo(data) {
			this.$request(
				"/shuziren/userUploadVideo/add",
				{
					videoUrl: data.fileUrl,
					coverUrl: data.coverUrl,
				},
				"POST",
				"application/json"
			).then((res) => {
				if (res.code === 200) {
					console.log("保存成功");
					this.getVideoList();
				}
			});
		},

		// 播放上传音频
		uploadAudioPlayFun(url) {
			if (!url) return this.$u.toast("请上传音频")
			if (this.audioId) {
				this.audioContext.destroy()
				this.audioContext = null
				this.audioId = 0
			}
			if (this.isUploadPlay) {
				this.innerAudioContext.pause();
				this.isUploadPlay = false
				return
			}
			this.isUploadPlay = true
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.autoplay = true;
			this.innerAudioContext.src = url
			this.innerAudioContext.onPlay(() => {
				console.log('开始播放');
			});
			this.innerAudioContext.onEnded(() => {
				console.log('播放结束');
				this.isUploadPlay = false
				this.innerAudioContext.destroy()
				this.innerAudioContext = null
			})
		},
		uploadFun(tempFilePaths) {
			let that = this
			that.$u.toast("正在整合视频，请耐心等待！")
			const uploadTask = uni.uploadFile({
				url: baseUrl.url + "/aiet-file-center/file/unlimitedFile",
				filePath: tempFilePaths,
				name: "file",
				formData: {
					"path": "shuziren/video"
				},
				timeout: 600000,
				success(uploadRes) {
					console.log(uploadRes)
					let data = JSON.parse(uploadRes.data)
					console.log(data)
					if (data.code === 200) {
						that.videoProgress = 0
						that.keepVideo(data.data)
					} else {
						that.$u.toast(data.msg)
					}
				},
				fail(uploadError) {
					console.log(uploadError)
					that.$u.toast(uploadError.errno === 5 ? '上传视频过大' : '网络状态不佳')
				}
			});
			console.log(uploadTask)
			uploadTask.onProgressUpdate(res => {
				console.log(res)
				that.videoProgress = res.progress
			})
		},

		// 上传视频素材
		chooseVideo() {
			let that = this
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				compressed: false,
				maxDuration: 30,
				success(res) {
					console.log(res)
					const tempFilePaths = res.tempFilePath
					console.log(tempFilePaths)
					uni.showLoading()
					uni.getVideoInfo({
						src: tempFilePaths,
						success(result) {
							console.log("获取原视频分辨率", result.width)
							if (result.width > 2048) {
								// 4K视频需要压缩
								if (result.width > result.height) {
									const scale = 1080 / result.height;
									that.compressVideo(tempFilePaths, result, scale);
								} else {
									const scale = 1080 / result.width;
									that.compressVideo(tempFilePaths, result, scale);
								}
							} else {
								// 非4K视频不用压缩
								uni.hideLoading()
								that.uploadFun(tempFilePaths)
							}
						},
						fail(err) {
							uni.hideLoading()
							console.log('素材上传失败', err)
						}
					})
				},
				fail(err) {
					uni.hideLoading()
					console.log('素材上传失败', err)
				}
			})
		},
		//压缩视频文件
		compressVideo(tempFilePaths, result, resolution) {
			let that = this;
			wx.compressVideo({
				src: tempFilePaths,
				bitrate: result.bitrate,
				fps: result.fps,
				resolution: resolution,
				success(RES) {
					console.log("获取压缩后文件临时路径", RES)
					that.uploadFun(RES.tempFilePath)
				},
				fail(err1) {
					uni.hideLoading()
					console.log("压缩视频失败", err1)
				}
			})
		}
	},
}
</script>
<style lang="less" scoped>
.popupVue {
	width: 620rpx;
	height: 100vh;
	padding: 30rpx;

	.h2 {
		font-weight: 700;
		font-size: 30rpx;
		color: #000;
		line-height: 1;
	}

	.upload {
		width: 180rpx;
		height: 60rpx;
		border-radius: 12rpx;
		background: #f8c329;
		text-align: center;
		line-height: 60rpx;
		color: #fff;
		font-size: 26rpx;
	}

	.scrollVue {
		width: 100%;
		height: calc(100vh - 110rpx);
		margin-top: 30rpx;
		box-sizing: border-box;

		.voiceVue {
			width: 100%;
			height: 100%;

			.item {
				width: 100%;
				height: 80rpx;
				background: #fff;
				overflow: hidden;
				border-radius: 12rpx;

				.playBtn {
					width: 80rpx;
					height: 80rpx;
					background: #ebeded;
				}

				.content {
					flex: 1;
					height: 80rpx;
					background: #f5f5f5;
				}
			}
		}

		.videoVue {
			width: 100%;

			.videoItem {
				width: 270rpx;
				height: 350rpx;
				background: #f5f5f5;
				margin-bottom: 20rpx;
				border-radius: 12rpx;
			}

			.botVue {
				width: 100%;
				height: 80rpx;
				padding: 0 15rpx;
				border-radius: 0 0 12rpx 12rpx;

				text {
					color: #333;
					font-size: 24rpx;
					font-weight: 600;
				}

				.btn {
					width: 90rpx;
					height: 46rpx;
					background: #f8c329;
					line-height: 47rpx;
					text-align: center;
					color: #fff;
					font-size: 24rpx;
					border-radius: 12rpx;
				}
			}

			.active {
				background: #f8c329;
				justify-content: center;

				text {
					color: #fff;
				}

				.btn {
					display: none;
				}
			}
		}
	}
}

.section {
	width: 690rpx;
	border-radius: 12rpx;
	background: #fff;
	padding: 30rpx;
	box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(178, 178, 178, 0.25),
		inset 0rpx 8rpx 8rpx 0rpx rgba(255, 255, 255, 0.25);

	.title {
		color: #000;
		font-weight: 600;
		font-size: 28rpx;
		line-height: 1;
	}
}

.inpVue {
	width: 690rpx;
	border-radius: 12rpx;
	background: #fff;
	padding: 30rpx;
	box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(178, 178, 178, 0.25),
		inset 0rpx 8rpx 8rpx 0rpx rgba(255, 255, 255, 0.25);

	.label {
		color: #000;
		font-weight: 600;
		font-size: 30rpx;
	}

	.aiBtn {
		width: 100rpx;
		height: 52rpx;
		line-height: 52rpx;
		color: #fff;
		background: #f8c329;
		border-radius: 12rpx;
		font-size: 24rpx;
		margin-left: 20rpx;
	}

	.startBtn {
		width: 100%;
		height: 88rpx;
		background: #f8c329;
		border-radius: 12rpx;
		line-height: 88rpx;
		text-align: center;
		color: #fff;
		font-size: 30rpx;
	}

	textarea {
		width: 100%;
		height: 160rpx;
		border-radius: 12rpx;
		border: 1rpx solid #ebeded;
		font-size: 28rpx;
		padding: 20rpx;
		margin-top: 20rpx;
		box-sizing: border-box;
		color: #000;
	}

	.audioVue {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ebeded;
		border-radius: 12rpx;

		.playBtn {
			width: 80rpx;
			height: 80rpx;
			background: #ebeded;
			border-radius: 12rpx 0 0 12rpx;
		}
	}

	input {
		width: 100%;
		height: 88rpx;
		border: 1rpx solid #ebeded;
		border-radius: 12rpx;
		margin-top: 20rpx;
		padding-left: 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		color: #000;
	}
}

.chooseVue {
	width: 100%;
	height: 88rpx;
	border: 1rpx solid #ebeded;
	border-radius: 12rpx;
	margin-top: 20rpx;
	padding: 0 10rpx 0 20rpx;

	text {
		color: #333;
	}
}
</style>
